<?php
namespace cms\modules\backend\controllers;

use Yii;
use cms\controllers\AuthController;
use app\models\Tplinfo;
use app\models\CoreConfig;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;


class TplController extends AuthController
{

    /*模板列表*/
    public function actionTplList()
    {
        $tplid = intval(isset($this->get['id'])?$this->get['id']:0);
        $path = isset($this->get['path'])?$this->get['path']:'';
        if($tplid == 0){//如果没有指定模板，就用默认模板
            $tplid = $this->template;
        }

        /*取出模板路径*/
        $tplinfo = Tplinfo::find()->select(['updataflag', 'tplfolder', 'folder'])
                  ->where('id = :id', [':id' => $tplid])->one();
        // P($tplinfo);
        $tplfolder = '';
        if($tplinfo->updataflag == 1 && !empty($tplinfo->tplfolder)){
            $tplfolder = $tplinfo->tplfolder;
        }else{
            $tplfolder = $tplid;
        }
        $folder = '';
        if(!empty($tplinfo->folder)){
            $folder = '/' . $tplinfo->folder;
        }
        $prefixPath = Yii::$app->basePath . '/web/' . Yii::$app->params['templates'] . '/' . $this->appid . '/' . $tplfolder . $folder;
        // p($prefixPath);
        if(empty($path)){
            $path = $prefixPath;
        }else{
            $path = $prefixPath . $path;
        }
        // echo $path;

        $fileList = Tool::dirList($path);

        /*过滤敏感目录，不要暴露给前端*/
        foreach($fileList as $k => $v){
            // unset($fileList[$k]['dir']);
            $fileList[$k]['dir'] = str_replace($prefixPath, '', $v['dir']);
        }
        // P($fileList);
        return Tool::showRes([0, '获取成功'], $fileList);
    }

    /*模板信息列表*/
    public function actionTplinfoList()
    {
        $tplinfo = new Tplinfo;
        $tplinfoList = $tplinfo::find()
                        ->where('app_id = :app_id or systpl = 2', [':app_id' => $this->app_id])
                        ->orderBy(['isdefault' => SORT_DESC, 'systpl' => SORT_ASC, 'id' => SORT_DESC])
                        ->asArray()->all();
        return Tool::showRes([0, '获取成功'], $tplinfoList);
    }

    /*添加模板信息*/
    public function actionAddTplInfo()
    {
        if($_FILES){//有文件上传
            $id = isset($this->get['id'])?intval($this->get['id']):0;
            // P($id);
            $info = $this->addTplzip($_FILES, $id);
            return $info;
        }else if(Yii::$app->request->isPost){//添加模板信息
            if(Yii::$app->request->isPost){
                $tplinfo = new Tplinfo;
                if($id = $tplinfo->addTplinfo($this->post, $this->app_id)){
                    /*如果选择是默认模板，需要把其他模板改成非默认模板*/
                    if($this->post['Tplinfo']['isdefault'] == 'true'){
                        /*注释原因，不需要考虑语言，使用下面一段代码*/
                        // $tplinfo->updateAll(['isdefault' => 1], 'id <> :id and lang = :lang', [':id' => $id, ':lang' => $this->post['Tplinfo']['lang']]);
                        $tplinfo->updateAll(['isdefault' => 1], 'id <> :id', [':id' => $id]);
                    }
                    $backInfo = [0, '添加视图模板成功'];//返回信息
                }else{
                    if($tplinfo->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $tplinfo->getErrors();//异常信息
                    }
                }
            };

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
    }

    /*修改模板信息*/
    public function actionModifyTplInfo()
    {
        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            // P($this->post);
            $id = isset($this->post['Tplinfo']['id'])?intval($this->post['Tplinfo']['id']):'';
            if(!$id){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    $tplinfo = new Tplinfo;
                    /*修改模板*/
                    if(!$tplinfo->modifyTplinfo($this->post, $id, $this->appid)){
                        $pass = false;
                        if($tplinfo->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $tplinfo->getErrors();//异常信息
                        }
                    }
                    if($pass){
                        /*如果选择是默认模板，需要把其他模板改成非默认模板*/
                        if($this->post['Tplinfo']['isdefault'] == 'true'){
                            /*注释原因，不需要考虑语言，使用下面一段代码*/
                            // $tplinfo->updateAll(['isdefault' => 1], 'id <> :id and lang = :lang', [':id' => $id, ':lang' => $this->post['Tplinfo']['lang']]);
                            $tplinfo->updateAll(['isdefault' => 1], 'app_id = :appid and id <> :id', [':appid' => $this->app_id, ':id' => $id]);
                        }

                        /*如果选择了默认模板，修改基本配置中的模板配置*/
                        // P($this->post['Tplinfo']['isdefault']);
                        if($this->post['Tplinfo']['isdefault'] == 'true'){
                            CoreConfig::updateAll(['template' => $id], 'app_id = :appid', [':appid' => $this->app_id]);
                        }
                    }

                    if($pass){
                        $backInfo = [0, '修改模板成功'];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*添加模板包*/
    private function addTplzip($file, $id = 0)
    {
        $tplinfo = new Tplinfo();
        if(($info = $tplinfo->upload($this->appid, $this->app_id, $id)) !== false){
            // P($info);
            return Tool::showRes([0, '上传成功'], $info);
        }else{
            if($tplinfo->hasErrors()){
                $backInfo = ErrMap::getError(10005);//返回信息
                $exception = $tplinfo->getErrors();//异常信息
            }
        }
        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*克隆仓库*/
    public function actionGitClone()
    {
        $tplid = intval($this->get['tplid']?$this->get['tplid']:0);
        if($tplid > 0){
            $tplinfo = Tplinfo::find()->select(['id', 'gitadd'])
                            ->where('id = :id and app_id = :app_id', [':id' => $tplid, ':app_id' => $this->app_id])
                            ->one();
            // P($tplinfo);
            if(!is_null($tplinfo) and $tplinfo->gitadd != ''){
                $tplid = $tplinfo->id;
                // echo $tplid;
                $path = Yii::$app->basePath . '/web/' . Yii::$app->params['templates'] . '/' . $this->appid . '/' . $tplid;
                if(!file_exists($path)){
                    mkdir($path, 0777, true);
                    chmod($path, 0777);
                }
                try{
                    if(!file_exists($path . '/.git')){//如有没有.git文件，说明没有clone过
                        exec('cd ../web/' . Yii::$app->params['templates'] . '/' . $this->appid . '/' . $tplid . ' && git clone ' . $tplinfo->gitadd . ' ./');
                        exec('cd ../web/' . Yii::$app->params['templates'] . '/' . $this->appid . '/' . $tplid . ' && git pull');
                    }else{
                        exec('cd ../web/' . Yii::$app->params['templates'] . '/' . $this->appid . '/' . $tplid . ' && git pull');
                    }
                    return Tool::showRes([0, '模板同步成功']);
                }catch(\Exception $exception){
                    return Tool::showRes(ErrMap::getError(20005));//模板同步失败
                };
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*读取的那个模板文件*/
    public function actionTplContent()
    {
        $tplid = intval(isset($this->get['id'])?$this->get['id']:0);
        /*取出模板信息*/
        $tplinfo = Tplinfo::find()->select(['updataflag', 'tplfolder', 'folder'])
                  ->where('id = :id', [':id' => $tplid])->one();
        $tplfolder = '';
        if($tplinfo->updataflag == 1 && !empty($tplinfo->tplfolder)){
            $tplfolder = $tplinfo->tplfolder;
        }else{
            $tplfolder = $tplid;
        }
        $prefixPath = Yii::$app->basePath . '/web/' . Yii::$app->params['templates'] . '/' . $this->appid . '/' . $tplfolder;
        $path = $prefixPath . (isset($this->get['path'])?$this->get['path']:'');
        // P($path);
        if(file_exists($path)){
            $fp = fopen($path, "r");
            $str = "";
            $buffer = 1024;//每次读取 1024 字节
            while(!feof($fp)){//循环读取，直至读取完整个文件
                $str .= fread($fp,$buffer);
            } 
            $str = str_replace("\r\n","<br />",$str);
            fclose($fp);
            // echo $str;
            return Tool::showRes([0, '获取成功'], $str);
        }else{
            return Tool::showRes(ErrMap::getError(20006));
        }
    }

}
